package com.lincoln.framework.controller.api;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lincoln.framework.common.ApiCode;
import com.lincoln.framework.common.ApiMessageHandler;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * api基础控制类
 * @author ssx
 */
public class BaseApiController {

	/**
	 * 处理api信息返回
	 */
	private ApiMessageHandler apiMessageHandler;
	
	/**
	 * 返回参数列表
	 */
	private Map<String, Object> ajaxAttributes = new HashMap<String, Object>();
	
	/**
	 * 检测请求是否来自iphone
	 * @return
	 */
	protected boolean requestFromIphone() {
		return true;
	}
	
	/**
	 * 检测请求是否来自android
	 * @return
	 */
	protected boolean requestFromAndroid() {
		return true;
	}
	
	/**
	 * 设置参数
	 * 
	 * @param name
	 * @param obj
	 */
	protected void setAttributes(String name, Object obj) {
		ajaxAttributes.put(name, obj);
	}
	
	/**
	 * 返回成功
	 */
	protected void returnSuccess() {
		this.returnData(ApiCode.REQUEST_SUCCESS);
	}
	
	/**
	 * 返回失败
	 */
	protected void returnError(int apiCode) {
		this.returnData(apiCode);
	}
	
	/**
	 * 返回失败
	 */
	protected void returnError(String msg) {
		this.returnData(msg);
	}
	
	/**
	 * 返回信息
	 * @param apiCode
	 */
	private void returnData(int apiCode) {
		this.apiMessageHandler = new ApiMessageHandler(this.getRequest(), this.getResponse());
		apiMessageHandler.returnData(apiCode, ajaxAttributes);
		ajaxAttributes.clear();
	}
	
	/**
	 * 返回信息
	 * @param apiCode
	 */
	private void returnData(String msg) {
		this.apiMessageHandler = new ApiMessageHandler(this.getRequest(), this.getResponse());
		apiMessageHandler.returnData(msg, ajaxAttributes);
		ajaxAttributes.clear();
	}
	
	/**
	 * 获取上下文HttpServletRequest
	 */
	protected HttpServletRequest getRequest() {
		RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
		return ((ServletRequestAttributes) attributes).getRequest();
	}

	/**
	 * 获取上下文HttpServletResponse
	 */
	protected HttpServletResponse getResponse() {
		RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
		return ((ServletRequestAttributes) attributes).getResponse();
	}
	
}
